package servlet;

import dao.UserDao;
import daomin.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
//        //获取请求参数
//        String username = request.getParameter("user");
//        String password = request.getParameter("password");
//        System.out.println(username+password);
//        //封装user对象
//        User loginUser = new User();
//        loginUser.setUsername(username);
//        loginUser.setPassword(password);
        //获取所有参数
        Map<String, String[]> map = request.getParameterMap();
        //创建user对象
        User loginUser = new User();
        //用Beanutlis来封装
        try {
            BeanUtils.populate(loginUser,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //调用UserDao的login方法
        UserDao da = new UserDao();
        User user = da.login(loginUser);
        System.out.println(user);

        //判断user
        if (user==null){
            //登录失败
            request.getRequestDispatcher("/failServlet").forward(request,response);
        }else{
            //登录成功,存储数据
            request.setAttribute("user",user);
            System.out.println(request.getAttribute("user"));
            //转发
            request.getRequestDispatcher("/successServlet").forward(request,response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
